﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AutoNotify
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //预设不显示在任务栏中
            this.ShowInTaskbar = false;
            //通知栏图标可见
            this.notifyIcon.Visible = true;

            #region set up NotifyIcon (右下角的图标设置)
            ContextMenuStrip menu = new ContextMenuStrip(this.components);

            ToolStripItem showWindowItem = menu.Items.Add("显示窗口");
            showWindowItem.Click += new EventHandler(showWindowItem_Click);

            ToolStripItem exitItem = menu.Items.Add("退出程序");
            exitItem.Click += new EventHandler(exitItem_Click);

            notifyIcon.ContextMenuStrip = menu;
            #endregion


            this.SetTimeout(() =>MessageBox.Show("hello with once!"), 1000);
        }

        //---------------------------------------------------------------------------
        //              Event handler
        //  事件的对应响应函数
        //---------------------------------------------------------------------------
        #region Event handler

        //显示窗口菜单
        void showWindowItem_Click(object sender, EventArgs e)
        {
            ShowMainForm();
        }

        //退出菜单
        void exitItem_Click(object sender, EventArgs e)
        {
            //此处才是真正退出：
            notifyIcon.Dispose();
            this.Dispose();
            Application.Exit();
        }

        //双击菜单时
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowMainForm();
        }

        //防止用户自己关闭，重写掉Close事件：
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        #endregion

        //---------------------------------------------------------------------------
        //              Private functions:
        //---------------------------------------------------------------------------
        #region private functions

        void ShowMainForm()
        {
            this.WindowState = FormWindowState.Normal;
            this.Show();
            this.Activate();
        }

        #endregion

    }
}
